/**
 *
 * @param {*} fn 要执行的函数
 * @param {*} delay 延迟执行的时间
 * @param {*} immediate 是否立即执行一次
 * @param {*} cb 回调函数，参数是执行函数的返回值
 * @returns
 */

export default function (fn, delay = 1000, immediate = false, cb) {
  let timer = null
  let isInvoke = true
  const _debounce = function (...args) {
    return new Promise((resolve, reject) => {
      if (immediate && isInvoke) {
        isInvoke = false
        const result = fn.apply(this, args)
        cb && cb(result)
        resolve(result)
      } else {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
          isInvoke = true
          timer = null
          const result = fn.apply(this, args)
          cb && cb(result)
          resolve(result)
        }, delay)
      }
    })
  }

  // 封装取消功能
  _debounce.cancel = function () {
    console.log('已取消')
    timer && clearTimeout(timer)
    timer = null
    isInvoke = true
  }

  return _debounce
}